﻿using Microsoft.AspNet.SignalR;
using MKAdmin.ToolKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace MKAdmin.Web.SignalR
{
    public class HubMain : Hub
    {
        public static List<UserChatIdentifyMainInfo> userHubMain = new List<UserChatIdentifyMainInfo>();
        public static object SetParamLock = new object();

        #region 初始化请求连接
        /// <summary>
        /// 初始化请求连接
        /// </summary>
        /// <param name="name"></param>
        public void InitConnection(UserChatIdentifyMainInfo clientInfo)
        {
            lock (SetParamLock)
            {
                if (clientInfo == null)
                {
                    clientInfo = new UserChatIdentifyMainInfo();
                }
                string connectionId = Context.ConnectionId;

                var connList = userHubMain.Where(q => q.ConnectionId == connectionId);
                if (!connList.Any())
                {
                    if (clientInfo.UserType == 1)
                    {
                        clientInfo.HeadUrl = "/images/userHead/0.jpg";
                        clientInfo.NickName = "系统客服";
                    }
                    else
                    {
                        clientInfo.HeadUrl = $"/images/userHead/{(new Random()).Next(1, 100).ToString()}.jpg";
                        clientInfo.NickName = (new Random()).Next(1000, 9999).ToString();
                    }
                    clientInfo.ConnectionId = connectionId;

                    //新增
                    userHubMain.Add(clientInfo);

                    //通知其他客户端有新用户上线
                    List<string> connectionIds = userHubMain.Where(q => q.ConnectionId != connectionId).Select(q => q.ConnectionId).ToList();

                    if (connectionIds != null && connectionIds.Count > 0)
                    {
                        Clients.Clients(connectionIds).noticeClientOnLine(clientInfo);
                    }

                    //通知自己所有客户端信息
                    var otherClients = userHubMain.Where(q => q.ConnectionId != connectionId).ToList();
                    if (otherClients.Any())
                    {
                        Clients.Client(connectionId).loadClientAll(otherClients);
                    }
                    //Clients.All.noticeClientOnLine(clientInfo);
                }

                Thread.Sleep(200);
            }
        }
        #endregion

        #region 离线
        /// <summary>
        /// 离线
        /// </summary>
        public override Task OnDisconnected(bool stopCalled)
        {
            string connectionId = Context.ConnectionId;
            //移除客户端链接
            userHubMain = userHubMain.Where(q => q.ConnectionId != connectionId).ToList();

            //通知客户端
            List<string> connectionIds = userHubMain.Select(q => q.ConnectionId).ToList();

            if (connectionIds != null && connectionIds.Count > 0)
            {
                Clients.Clients(connectionIds).noticeClientOnDisconnected(connectionId);
            }

            return base.OnDisconnected(stopCalled);
        }
        #endregion

        #region 发送消息
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="groupIdentify"></param>
        public void SendMsg(ChatMsgParamMainInfo content)
        {
            try
            {
                sendMsgToMine(content);

                sendMsgToClient(content);
            }
            catch (Exception ex)
            {
                StringBuilder itemS = new StringBuilder();
                itemS.AppendLine("发送消息异常:" + ex.Message);
                LogHelper.Error(itemS.ToString());
            }
        }
        #endregion

        #region 自动回复消息
        /// <summary>
        /// 自动回复消息
        /// </summary>
        /// <param name="content"></param>
        public void AutoReplyMsg(ChatMsgParamMainInfo content)
        {
            try
            {
                Thread.Sleep(500);

                List<ChatMsgParamMainInfo> contentList = new List<ChatMsgParamMainInfo>();
                if (content.Text == "1")
                {
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 0,
                        Text = "微信扫下方二维码添加站长吧",
                        ImgUrl = ""
                    });
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 1,
                        Text = "",
                        ImgUrl = "http://www.mikeblog.cn/images/pop/myQrCode2.png"
                    });
                }
                else if (content.Text == "2")
                {
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 0,
                        Text = "微信扫一扫进入'抽奖'页面进行抽奖",
                        ImgUrl = ""
                    });
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 1,
                        Text = "",
                        ImgUrl = "http://www.mikeblog.cn/images/pop/10003.png"
                    });
                }
                else if (content.Text == "3")
                {
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 0,
                        Text = "别闹了，哪来的私照，咋是正经人",
                        ImgUrl = ""
                    });
                }
                else
                {
                    contentList.Add(new ChatMsgParamMainInfo()
                    {
                        ReceiverConnectionId = content.ReceiverConnectionId,
                        MsgType = 0,
                        Text = "现在是客服休息时间<br/><br/>回复1 添加站长微信号<br/><br/>回复2 免费抽奖<br/><br/>回复3 看客服MM私照",
                        ImgUrl = ""
                    });
                }

                foreach (var list in contentList)
                {
                    sendMsgToMine(list);
                    sendMsgToClient(list);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                StringBuilder itemS = new StringBuilder();
                itemS.AppendLine("自动回复发送消息异常:" + ex.Message);
                LogHelper.Error(itemS.ToString());
            }
        }
        #endregion

        #region 新用户欢迎语
        /// <summary>
        /// 新用户欢迎语
        /// </summary>
        /// <param name="content"></param>
        public void AutoReplyWelcomeMsg(string connectionId)
        {
            try
            {
                Thread.Sleep(500);

                List<ChatMsgParamMainInfo> contentList = new List<ChatMsgParamMainInfo>();
                contentList.Add(new ChatMsgParamMainInfo()
                {
                    ReceiverConnectionId = connectionId,
                    MsgType = 0,
                    Text = "现在是客服休息时间<br/><br/>回复1 添加站长微信号<br/><br/>回复2 免费抽奖<br/><br/>回复3 看客服MM私照",
                    ImgUrl = ""
                });

                foreach (var list in contentList)
                {
                    sendMsgToMine(list);
                    sendMsgToClient(list);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                StringBuilder itemS = new StringBuilder();
                itemS.AppendLine("新用户欢迎语发送消息异常:" + ex.Message);
                LogHelper.Error(itemS.ToString());
            }
        }
        #endregion

        //通知自己发送完成
        private void sendMsgToMine(ChatMsgParamMainInfo content)
        {
            string senderConnectionId = content.ReceiverConnectionId;

            string senderNickName = "";
            string senderHeadUrl = "";
            var sendUserInfo = userHubMain.Where(q => q.ConnectionId == Context.ConnectionId);
            if (sendUserInfo.Any())
            {
                senderNickName = sendUserInfo.FirstOrDefault().NickName;
                senderHeadUrl = sendUserInfo.FirstOrDefault().HeadUrl;
            }
            var msgContent = new
            {
                senderConnectionId = senderConnectionId,
                senderNickName = senderNickName,
                senderHeadUrl = senderHeadUrl,
                msgType = content.MsgType,
                text = content.Text,
                imgUrl = content.ImgUrl,
                sendTime = DateTime.Now
            };
            Clients.Client(Context.ConnectionId).sendComplete(msgContent);
        }

        /// <summary>
        /// 发送消息给用户
        /// </summary>
        private void sendMsgToClient(ChatMsgParamMainInfo content)
        {
            string senderConnectionId = Context.ConnectionId;

            string senderNickName = "";
            string senderHeadUrl = "";
            var recevierInfo = userHubMain.Where(q => q.ConnectionId == Context.ConnectionId);
            if (recevierInfo.Any())
            {
                senderNickName = recevierInfo.FirstOrDefault().NickName;
                senderHeadUrl = recevierInfo.FirstOrDefault().HeadUrl;
            }
            var msgContent = new
            {
                senderConnectionId = senderConnectionId,
                senderNickName = senderNickName,
                senderHeadUrl = senderHeadUrl,
                msgType = content.MsgType,
                text = content.Text,
                imgUrl = content.ImgUrl,
                sendTime = DateTime.Now
            };
            Clients.Client(content.ReceiverConnectionId).acceptMsgToClient(msgContent);
        }
    }

    /// <summary>
    /// 建立链接实体对象
    /// </summary>
    public class UserChatIdentifyMainInfo
    {
        /// <summary>
        /// 客户端推送消息链接Id
        /// </summary>
        public string ConnectionId { get; set; }
        /// <summary>
        /// 聊天昵称
        /// </summary>
        public string NickName { get; set; }
        /// <summary>
        /// 聊天头像
        /// </summary>
        public string HeadUrl { get; set; }
        /// <summary>
        /// 用户类型 0:普通用户  1:客服账号
        /// </summary>
        public int UserType { get; set; }
        /// <summary>
        /// 用户登录账号Id
        /// </summary>
        public int UserId { get; set; }
        /// <summary>
        /// 消息时间
        /// </summary>
        public DateTime SendTime { get; set; } = DateTime.Now;
    }

    /// <summary>
    /// 聊天实体对象
    /// </summary>
    public class ChatMsgParamMainInfo
    {
        /// <summary>
        /// 接收者对象客户端Id(用来推送消息)
        /// </summary>
        public string ReceiverConnectionId { get; set; }
        /// <summary>
        /// 消息类型（0:文字 1:图片）
        /// </summary>
        public int MsgType { get; set; }
        /// <summary>
        /// 文字内容
        /// </summary>
        public string Text { get; set; }
        /// <summary>
        /// 图片Url
        /// </summary>
        public string ImgUrl { get; set; }
    }
}